package com.ruoyi.system.api.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.BindReturn;
import com.ruoyi.system.api.domain.BindReturnPartInfo;
import com.ruoyi.system.api.service.PokeRequestServe;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.mapper.AnnexMapper;
import com.ruoyi.system.api.domain.Annex;
import com.ruoyi.system.api.service.IAnnexService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;

/**
 * 附件Service业务层处理
 *
 * @author shihx
 * @date 2020-03-03
 */
@Service
public class AnnexServiceImpl implements IAnnexService {
    @Autowired
    private AnnexMapper annexMapper;

    @Autowired
    private PokeRequestServe pokeRequestServe;

    /**
     * 配置文件
     */
    @Autowired
    private Global global;

    /**
     * 查询附件
     *
     * @param id 附件ID
     * @return 附件
     */
    @Override
    public Annex selectAnnexById(Long id) {
        return annexMapper.selectAnnexById(id);
    }

    /**
     * 查询附件列表
     *
     * @param annex 附件
     * @return 附件
     */
    @Override
    public List<Annex> selectAnnexList(Annex annex) {
        return annexMapper.selectAnnexList(annex);
    }

    /**
     * 新增附件
     *
     * @param annex 附件
     * @return 结果
     */
    @Override
    public int insertAnnex(Annex annex) {
        annex.setCreateTime(DateUtils.getNowDate());
        return annexMapper.insertAnnex(annex);
    }

    /**
     * 修改附件
     *
     * @param annex 附件
     * @return 结果
     */
    @Override
    public int updateAnnex(Annex annex) {
        annex.setUpdateTime(DateUtils.getNowDate());
        return annexMapper.updateAnnex(annex);
    }

    /**
     * 删除附件对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAnnexByIds(String ids) {
        return annexMapper.deleteAnnexByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除附件信息
     *
     * @param id 附件ID
     * @return 结果
     */
    @Override
    public int deleteAnnexById(Long id) {
        return annexMapper.deleteAnnexById(id);
    }

    /**
     * 根据helpid、serviceNo查询附件信息
     *
     * @param serviceNo serviceNo
     * @param helpId    辅助id
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020-03-03 16:10
     */
    @Override
    public ResponseWithData<?> selectAnnexsByServiceNoAndHelpId(String serviceNo, String helpId) {
        List<Annex> datas = annexMapper.selectAnnexListByHelpIdAndServiceNo(serviceNo, helpId);
        if (null == datas) {
            datas = new ArrayList<>();
        }
        return new ResponseWithData<>().success(datas).code(200);
    }

    /**
     * 服务报告附件上传 单文件上传
     *
     * @param file
     * @param request
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/12 3:45 下午
     */
    @Override
    public ResponseWithData<?> uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String serviceNo = request.getParameter("serviceNo");
        String fseName = request.getParameter("fseName");
        String enginnerId = request.getParameter("enginnerId");
        String desc = request.getParameter("desc");
        String helpId = request.getParameter("helpId");
        if (StringUtils.isEmpty(serviceNo)) {
            return new ResponseWithData<>().error().msg("serviceNo cannot be empty");
        }
        if (StringUtils.isEmpty(fseName)) {
            return new ResponseWithData<>().error().msg("fseName cannot be empty");
        }
        if (StringUtils.isEmpty(enginnerId)) {
            return new ResponseWithData<>().error().msg("enginnerId cannot be empty");
        }
        if (StringUtils.isEmpty(helpId)) {
            return new ResponseWithData<>().error().msg("helpId cannot be empty");
        }

        String originalFilenames = file.getOriginalFilename();

        String filename = DateUtils.dateTimeNow("yyyyMMddHHmmssSSS") + "-" + originalFilenames;
        String ext = FilenameUtils.getExtension(originalFilenames);
        String filenames = filename;

        Annex annex = new Annex();
        annex.setDelFlag("0");
        annex.setSyncFlag("0");
        annex.setCreateTime(new Date());
        annex.setEnginnerId(enginnerId);
        annex.setServiceNo(serviceNo);
        annex.setFseName(fseName);
        annex.setHelpId(helpId);
        annex.setFileDescription(desc);
        annex.setFileName(originalFilenames);
        annex.setFileType(ext);
        annex.setFileSize(file.getSize() + "");
        annex.setFilePath("/service/" + serviceNo + "/" + filenames);

        String profile = Global.getProfile();
        File fileDir = new File(profile + "/service/" + serviceNo + "/");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        System.out.println(fileDir.getAbsolutePath());

        String pathName = fileDir.getAbsolutePath() + "/" + filenames;
        file.transferTo(new File(pathName));

        annexMapper.insertAnnex(annex);

        return new ResponseWithData<>().success(annex).code(200);
    }





    @Override
    public ResponseWithData<?> uploadFileReport(MultipartFile file, HttpServletRequest request) throws IOException {
        String serviceNo = request.getParameter("serviceNo");
        String fseName = request.getParameter("fseName");
        String enginnerId = request.getParameter("enginnerId");
        String desc = request.getParameter("desc");
        String helpId = request.getParameter("helpId");
        String sort = request.getParameter("sort");
        if (StringUtils.isEmpty(serviceNo)) {
            return new ResponseWithData<>().error().msg("serviceNo cannot be empty");
        }
        if (StringUtils.isEmpty(fseName)) {
            return new ResponseWithData<>().error().msg("fseName cannot be empty");
        }
        if (StringUtils.isEmpty(enginnerId)) {
            return new ResponseWithData<>().error().msg("enginnerId cannot be empty");
        }
        if (StringUtils.isEmpty(helpId)) {
            return new ResponseWithData<>().error().msg("helpId cannot be empty");
        }
        if (StringUtils.isEmpty(sort)) {
            return new ResponseWithData<>().error().msg("sort cannot be empty");
        }
        String originalFilenames = file.getOriginalFilename();
        String originalFilename = FilenameUtils.getBaseName(originalFilenames);
        String filename = DateUtils.dateTimeNow("yyyyMMddHHmmssSSS") + "-" + originalFilename;
        String ext = FilenameUtils.getExtension(originalFilenames);
        String filenames = filename + "." + ext;
        Annex annex = new Annex();
        annex.setSort(sort);
        annex.setEnginnerId(enginnerId);
        annex.setServiceNo(serviceNo);
        List<Annex> anList = annexMapper.selectAnnexList(annex);

        annex.setDelFlag("0");
        annex.setSyncFlag("0");
        annex.setCreateTime(new Date());
        annex.setFseName(fseName);
        annex.setHelpId(helpId);
        annex.setFileDescription(desc);
        annex.setFileName(originalFilenames);
        annex.setFileType(ext);
        annex.setFileSize(file.getSize() + "");
        annex.setFilePath("/service/" + serviceNo + "/" + filenames);

        String profile = Global.getProfile();
        File fileDir = new File(profile + "/service/" + serviceNo + "/");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        System.out.println(fileDir.getAbsolutePath());

        String pathName = fileDir.getAbsolutePath() + "/" + filenames;
        file.transferTo(new File(pathName));
        if(anList.size() > 0){  //覆盖更新
            annexMapper.updateAnnex(annex);
        }else{
            annexMapper.insertAnnex(annex);
        }
        return new ResponseWithData<>().success(annex).code(200);
    }

    @Override
    public ResponseWithData<?> uploadFileParts(MultipartFile file, HttpServletRequest request) throws IOException {
//        String serviceNo = request.getParameter("serviceNo");
        String fseName = request.getParameter("fseName");
        String enginnerId = request.getParameter("enginnerId");
        String desc = request.getParameter("desc");
        String helpId = request.getParameter("helpId");
        String sort = request.getParameter("sort");
        String timestamp = String.valueOf(System.currentTimeMillis()); //获取系统时间戳
        if (StringUtils.isEmpty(fseName)) {
            return new ResponseWithData<>().error().msg("fseName cannot be empty");
        }
        if (StringUtils.isEmpty(enginnerId)) {
            return new ResponseWithData<>().error().msg("enginnerId cannot be empty");
        }
        String originalFilenames = file.getOriginalFilename();
        String originalFilename = FilenameUtils.getBaseName(originalFilenames);
        String filename = DateUtils.dateTimeNow("yyyyMMddHHmmssSSS") + "-" + originalFilename;
        String ext = FilenameUtils.getExtension(originalFilenames);
        String filenames = filename + "." + ext;
        Annex annex = new Annex();
//        annex.setSort(sort);
        annex.setEnginnerId(enginnerId);
//        annex.setServiceNo(serviceNo);
//        List<Annex> anList = annexMapper.selectAnnexList(annex);

        annex.setDelFlag("0");
        annex.setSyncFlag("0");
        annex.setCreateTime(new Date());
        annex.setFseName(fseName);
//        annex.setHelpId(helpId);
        annex.setFileDescription(desc);
        annex.setFileName(originalFilenames);
        annex.setFileType(ext);
        annex.setFileSize(file.getSize() + "");
        annex.setFilePath("/parts/" + enginnerId + "/" + timestamp + "/" + filenames);

        String profile = Global.getProfile();
        File fileDir = new File(profile + "/parts/" + enginnerId + "/" + timestamp + "/");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        System.out.println(fileDir.getAbsolutePath());

        String pathName = fileDir.getAbsolutePath() + "/" + filenames;
        file.transferTo(new File(pathName));
        annexMapper.insertAnnex(annex);
        return new ResponseWithData<>().success(annex).code(200);
    }

    @Override
    public ResponseWithData<?> uploadWorkReportPic(MultipartFile file, HttpServletRequest request) throws IOException{
        // 参数
        String originalFilenames = file.getOriginalFilename();
        String FileSuffix = originalFilenames.substring(originalFilenames.lastIndexOf(".") + 1);
        String originalFilename = FilenameUtils.getBaseName(originalFilenames);
        String filename = DateUtils.dateTimeNow("yyyyMMddHHmmssSSS") + "-" + originalFilenames;
        String enginnerId = request.getParameter("enginnerId");
        String serviceNo = request.getParameter("serviceNo");
        String helpId = request.getParameter("helpId");
        // base64
        BASE64Encoder base64Encoder =new BASE64Encoder();
//        String base64EncoderImg = file.getOriginalFilename()+","+ base64Encoder.encode(file.getBytes());
        String base64EncoderImg =
     //           "data:image/"+FileSuffix+";base64," +
                        base64Encoder.encode(file.getBytes()).replaceAll("\r\n","");
        // cc地址
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        String ccName = "三个报告附件上传";
        String ccType = "";
        if (helpId.equals("1")) {
            // 工作报告附件上传
            url.append("uploadWorkReportPic.asmx/uploadWorkReportPichandle");
            ccName = "工作报告附件上传";
            ccType = "uploadWorkReportPicHandle";
        } else if (helpId.equals("2")) {
            // 上传签字验收报告附件
            url.append("uploadSignaturePic.asmx/uploadSignaturePichandle");
            ccName = "上传签字验收报告附件";
            ccType = "uploadSignaturePichandle";
        } else if (helpId.equals("3")) {
            // 上传客户现场确认单附件
            url.append("uploadCustomerAcceptPic.asmx/uploadCustomerAcceptPichandle");
            ccName = "上传客户现场确认单附件";
            ccType = "uploadCustomerAcceptPic";
        }
        // 调cc接口
        StringBuffer postParam = new StringBuffer();
        postParam.append("enginner_id=").append(enginnerId);
        postParam.append("&service_no=").append(serviceNo);
        postParam.append("&pic_name=").append(filename);
        postParam.append("&b=").append(base64EncoderImg);
        return pokeRequestServe.transPost(url.toString(), ccName, ccType, postParam.toString());
    }

	@Override
	public ResponseWithData<?> getServiceFileHandle(String serviceNo) {
		
		// cc地址
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("getServiceFile.asmx/getServiceFileHandle?service_no=");
        url.append(serviceNo);
        String ccName="获取服务报告";
        String ccType="getServiceFileHandle";
        StringBuffer postParam = new StringBuffer();
        postParam.append("").append(serviceNo);
        return pokeRequestServe.transGet(url.toString(), ccName, ccType);
	}
    @Override
    public ResponseWithData<?> getServiceContractHandle(String serviceNo){
        // cc地址
        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("getServiceContract.asmx/getServiceContractHandle?service_no=");
        url.append(serviceNo);
        String ccName="获取服务通知关联合同信息";
        String ccType="getServiceContractHandle";
        StringBuffer postParam = new StringBuffer();
        postParam.append("").append(serviceNo);
        return pokeRequestServe.transGet(url.toString(), ccName, ccType);
    }
}
